const Mock = require('mockjs')
const { list: listOrgUnits, find: findOrgUnit } = require('./org-units')

let SupportReturnMoneyShops = []
const orgUnitsPage = listOrgUnits(1, 10, 1)
for (let i = 0; i < orgUnitsPage.data.records.length; ++i) {
  SupportReturnMoneyShops.push(Mock.mock({
    id: i + 1,
    orgUnitId: orgUnitsPage.data.records[i].id
  }))
}

function add(item) {
  const r = JSON.parse(JSON.stringify(item))
  r.id = SupportReturnMoneyShops[SupportReturnMoneyShops.length - 1].id + 1
  SupportReturnMoneyShops.push(r)
}

function list(page, limit, orgUnitId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  let mocks = SupportReturnMoneyShops.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    return true
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1)).map(item => {
    const o = findOrgUnit(item.orgUnitId)
    if (o) {
      item.orgUnitName = o.name
    }
    return item
  })
  return { success: true, data: { total: total, records: mocks }}
}

function remove(id) {
  id = id ? parseInt(id) : null
  SupportReturnMoneyShops = SupportReturnMoneyShops.filter(item => {
    return item.id !== id
  })
}

module.exports = { list, add, remove }
